package top.hudk.advantage.service;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.net.www.http.HttpClient;
import top.hudk.advantage.entity.LoginResultEntity;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

@Service
public class LoginService {

    public LoginResultEntity login(String code) throws URISyntaxException, IOException {

        String appId = "wx0c2f95a159d8a974";
        String appSecret = "92c6304ab2139022fec2269eca10a03c";
        String grant_type = "authorization_code";
        LoginResultEntity loginResultEntity = null;
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpGet get = new HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type="+grant_type);

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(get);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                loginResultEntity = JSON.parseObject(content, LoginResultEntity.class);
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

        return loginResultEntity;
    }


}
